<template>
    <!-- el-table -->
    <el-button @click="editDish()">新增菜品</el-button>
    <!-- 输入搜索框 -->
    <el-input v-model="nameSearch" placeholder="请输入搜索内容" style="width: 200px; margin-left:20px" />
    <el-button @click="searchDish" type='primary'>搜索</el-button>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="image" label="图片" width="160">
            <template #default="{ row }">
                <div>
                    <img v-if="row.image" :src="base.baseUrl + row.image" alt="图片加载失败"
                        style="width: 140px; height: 140px;" />
                    <img v-else src="../assets/noImage.png" alt="图片加载失败" style="width: 140px; height: 140px;" />
                </div>
            </template>
        </el-table-column>
        <el-table-column prop="name" label="菜名" width="300" />
        <el-table-column prop="price" label="价格" width="180" />
        <el-table-column prop="description" label="描述" />

        <el-table-column label="操作">
            <template #default="{ row }">
                <el-button type="primary" @click="editDish(row)">编辑</el-button>
                <el-button type="danger" @click="deleteDish(row.id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination background :size="pageSize" layout="prev, pager, next" :total="total"
        @current-change="handleCurrentChange" />

    <!-- 编辑弹窗 -->
    <el-dialog title="编辑菜品" v-model="dishWidow" destroy-on-close>
        <el-form>
            <el-form-item label="菜名">
                <el-input v-model="name" />
            </el-form-item>
            <el-form-item label="价格">
                <el-input-number v-model="price" :precision="2" :step="0.1" />
            </el-form-item>
            <el-form-item label="描述">
                <el-input v-model="description" />
            </el-form-item>
            <el-form-item label="图片">
                <el-upload :action="uploadFileUrl" list-type="picture-card" :onPreview="handlePictureCardPreview"
                    :on-remove="handleRemove" :file-list="fileList" :limit='1' :on-success="handleSuccess"
                    :before-upload="beforeAvatarUpload">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <!-- 上传过一张图片后隐藏 -->
                    <template #tip>
                        <div class="el-upload__tip">只能上传jpg/png文件</div>
                    </template>

                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm()">提交</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <el-dialog v-model="dialogVisible" width="50%">
        <img style="height: 100%; width: 100%;" :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Api } from '@/api/index.js'
import base from '@/api/base.js'
const uploadFileUrl = base.baseUrl + base.uploadFile
const dialogVisible = ref(false)



const dishWidow = ref(false)
const nameSearch = ref('')
const name = ref('')
const price = ref('')
const description = ref('')
const fileList = ref([])
const fileUrl = ref('')
const handleRemove = (file, fileList) => {
    fileUrl.value = ''
}
const handleSuccess = (res, file, fileList) => {
    if (res.status === 200) {
        fileUrl.value = res.filePaths[0]
        ElMessage.success('上传成功')
    } else {
        ElMessage.error('上传失败')
    }
}

const beforeAvatarUpload = (rawFile) => {
    // jpg或者png
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('必须是jpg或者png图片')
        return false
    } else if (rawFile.size / 99999 / 9999 > 2) {
        return false
    }
    return true
}

const dialogImageUrl = ref('')
const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
}

const searchDish = () => {
    Api.getDishList({
        page: page.value,
        pageSize: 10,
        name: nameSearch.value
    }).then((res) => {
        tableData.value = res.data
        total.value = res.total
    }).catch((err) => {
        ElMessage.error(err.response.data.message)
    })
}


const submitForm = () => {
    // 校验
    if (name.value === '') {
        ElMessage.error('请输入菜名')
        return
    }
    if (price.value === '') {
        ElMessage.error('请输入价格')
        return
    }
    if (fileUrl.value === '') {
        ElMessage.error('请上传图片')
    }

    if (mode.value) {
        Api.updateDish({
            id: mode.value,
            name: name.value,
            price: price.value,
            description: description.value,
            image: fileUrl.value
        }).then((res) => {
            ElMessage.success('编辑成功')
            dishWidow.value = false
            getDishList()

        }).catch((err) => {
            ElMessage.error(err.response.data.message)
        })
    }
    else {
        Api.addDish({
            name: name.value,
            price: price.value,
            description: description.value,
            image: fileUrl.value
        }).then((res) => {
            ElMessage.success('新增成功')
            dishWidow.value = false
            getDishList()
        }).catch((err) => {
            ElMessage.error(err.response.data.message)
        })
    }

}
const getDishList = () => {
    Api.getDishList({
        page: page.value,
        pageSize: 10,
        name: ''
    }).then((res) => {
        tableData.value = res.data
        total.value = res.total
    }).catch((err) => {
        ElMessage.error(err.response.data.message)
    })
}
const mode = ref('')
const editDish = (row) => {
    dishWidow.value = true;
    mode.value = row?.id || '';
    name.value = row?.name || '';
    price.value = row?.price || '';
    description.value = row?.description || '';
    console.log(mode.value);

    // 如果 row.image 不是空的，创建一个包含图片链接的对象，并更新 fileList
    if (row?.image) {
        fileList.value = [{
            name: 'image', // 文件名
            url: 'http://localhost:8080' + row.image, // 文件链接
        }];
    } else {
        fileList.value = [];
    }

    fileUrl.value = row.image;
};


const tableData = ref([])
const page = ref(1)
const pageSize = ref(10)

const total = ref(0)

onMounted(() => {
    getDishList()
})

const handleCurrentChange = (val) => {
    Api.getDishList({
        page: val,
        pageSize: 10,
        name: ''
    }).then((res) => {
        tableData.value = res.data
        total.value = res.total
    }).catch((err) => {
        ElMessage.error(err.response.data.message)
    })
}

const deleteDish = (id) => {
    Api.deleteDish({ id }).then((res) => {
        ElMessage.success('删除成功')
        Api.getDishList({
            page: page.value,
            pageSize: 10,
            name: ''
        }).then((res) => {
            tableData.value = res.data
            total.value = res.total
        }).catch((err) => {
            ElMessage.error(err.response.data.message)
        })
    }
    ).catch((err) => {
        ElMessage.error(err.response.data.message)
    })
}
</script>